<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="ages" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="value">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addfn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="splicefn(index)">删除</button>
            <button @click="chengfn(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      uname: "",
      ages: "",
      value: "",
      ind: "",
      list: [
        {
          name: "张三",
          age: 18,
          sex: "男",
        },
        {
          name: "李四",
          age: 18,
          sex: "男",
        },
      ],
    };
  },
  methods: {
    addfn() {
      if (this.uname === "" || this.ages === "" || this.value === "")
        return alert("请输入完整信息");
      if (this.list[this.ind]) {
        //如果我点击的是我 是我输入的jiu
        //疑问是怎么判断我点击的增加还是修改  ？？
        //
        this.list.splice(this.ind, 1, {
          name: this.uname,
          age: this.ages,
          sex: this.value,
        });
        this.ind = "";
      } else {
        this.list.push({
          name: this.uname,
          age: this.ages,
          sex: this.value,
        });
      }
      (this.uname = ""), (this.ages = ""), (this.value = "");
    },
    splicefn(index) {
      this.list.splice(index, 1); //传过来索引 索引删除
    },
    chengfn(index) {
      // 还有是怎么 点击编辑又回到上面输入框的
      (this.uname = this.list[index].name),
        (this.ages = this.list[index].age),
        (this.value = this.list[index].sex);
      this.ind = index;
    },
  },
};
</script>
